package com.ruoyi.eduManage.service.impl;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StudentNoUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.eduManage.domain.EduStudent;
import com.ruoyi.eduManage.domain.EduClass;
import com.ruoyi.eduManage.domain.EduStudentPointsLog;
import com.ruoyi.eduManage.mapper.EduStudentMapper;
import com.ruoyi.eduManage.mapper.EduClassMapper;
import com.ruoyi.eduManage.service.IEduStudentService;
import com.ruoyi.eduManage.service.IEduClassService;
import com.ruoyi.eduManage.service.IEduStudentPointsLogService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 学生信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-26
 */
@Service
public class EduStudentServiceImpl implements IEduStudentService
{
    @Autowired
    private EduStudentMapper eduStudentMapper;

    @Autowired
    private EduClassMapper eduClassMapper;
    
    @Autowired
    private IEduClassService eduClassService;

    @Autowired
    private IEduStudentPointsLogService pointsLogService;


    /**
     * 查询学生信息
     * 
     * @param studentId 学生信息主键
     * @return 学生信息
     */
    @Override
    public EduStudent selectEduStudentByStudentId(Long studentId)
    {
        return eduStudentMapper.selectEduStudentByStudentId(studentId);
    }

    /**
     * 查询学生信息列表
     * 
     * @param eduStudent 学生信息
     * @return 学生信息
     */
    @Override
    public List<EduStudent> selectEduStudentList(EduStudent eduStudent)
    {
        return eduStudentMapper.selectEduStudentList(eduStudent);
    }

    /**
     * 新增学生信息
     * 
     * @param eduStudent 学生信息
     * @return 结果
     */
    @Override
    public int insertEduStudent(EduStudent eduStudent)
    {
        eduStudent.setCreateTime(DateUtils.getNowDate());
        if (eduStudent.getPoints() == null) {
            eduStudent.setPoints(0);
        }
        return eduStudentMapper.insertEduStudent(eduStudent);
    }

    /**
     * 修改学生信息
     * 
     * @param eduStudent 学生信息
     * @return 结果
     */
    @Override
    public int updateEduStudent(EduStudent eduStudent)
    {
        eduStudent.setUpdateTime(DateUtils.getNowDate());
        // 记录积分变更
        try {
            if (eduStudent.getStudentId() != null) {
                EduStudent before = eduStudentMapper.selectEduStudentByStudentId(eduStudent.getStudentId());
                if (before != null) {
                    Integer beforePoints = before.getPoints() == null ? 0 : before.getPoints();
                    Integer afterPoints = eduStudent.getPoints() == null ? beforePoints : eduStudent.getPoints();
                    int change = afterPoints - beforePoints;
                    if (change != 0) {
                        EduStudentPointsLog log = new EduStudentPointsLog();
                        log.setStudentId(eduStudent.getStudentId());
                        log.setStudentName(before.getStudentName());
                        log.setBeforePoints(beforePoints);
                        log.setChangeAmount(change);
                        log.setAfterPoints(afterPoints);
                        // 优先使用传入的 remark 作为日志原因
                        String reason = StringUtils.isNotBlank(eduStudent.getRemark()) ? eduStudent.getRemark() : "手动修改学生积分";
                        log.setReason(reason);
                        log.setOperator(eduStudent.getUpdateBy());
                        log.setCreateTime(DateUtils.getNowDate());
                        pointsLogService.insertEduStudentPointsLog(log);
                    }
                }
            }
        } catch (Exception ignore) {}

        return eduStudentMapper.updateEduStudent(eduStudent);
    }

    /**
     * 批量删除学生信息
     * 
     * @param studentIds 需要删除的学生信息主键
     * @return 结果
     */
    @Override
    public int deleteEduStudentByStudentIds(Long[] studentIds)
    {
        // 在删除学生前，先获取学生信息，用于更新班级学生人数
        for (Long studentId : studentIds)
        {
            EduStudent student = eduStudentMapper.selectEduStudentByStudentId(studentId);
            if (student != null && student.getClassId() != null)
            {
                EduClass eduClass = new EduClass();
                eduClass.setClassCode(student.getClassId());
                eduClass.setDelFlag("0");
                List<EduClass> classList = eduClassMapper.selectEduClassList(eduClass);
                if (!CollectionUtils.isEmpty(classList)) {
                    EduClass temp = classList.get(0);
                    if (temp != null)
                    {
                        // 更新班级学生人数，减少1
                        eduClassService.updateStudentCount(temp.getClassCode(), -1);
                    }
                }
            }
        }
        return eduStudentMapper.deleteEduStudentByStudentIds(studentIds);
    }

    /**
     * 删除学生信息信息
     * 
     * @param studentId 学生信息主键
     * @return 结果
     */
    @Override
    public int deleteEduStudentByStudentId(Long studentId)
    {
        // 在删除学生前，先获取学生信息，用于更新班级学生人数
        EduStudent student = eduStudentMapper.selectEduStudentByStudentId(studentId);
        if (student != null && student.getClassId() != null)
        {
            EduClass eduClass = new EduClass();
            eduClass.setClassCode(student.getClassId());
            eduClass.setDelFlag("0");
            List<EduClass> classList = eduClassMapper.selectEduClassList(eduClass);
            if (!CollectionUtils.isEmpty(classList)) {
                EduClass temp = classList.get(0);
                if (temp != null)
                {
                    // 更新班级学生人数，减少1
                    eduClassService.updateStudentCount(temp.getClassCode(), -1);
                }
            }
        }
        return eduStudentMapper.deleteEduStudentByStudentId(studentId);
    }
    
    @Override
    public String importStudent(MultipartFile file, String fileName, Long classId)
    {
        // 1. 文件名格式校验
        Pattern pattern = Pattern.compile("^(\\d{3})_班级学生信息\\.(xlsx|xls)$");
        Matcher matcher = pattern.matcher(fileName);
        if (!matcher.matches()) {
            return "文件名格式不正确，请使用'xxx_班级学生信息.xlsx'格式，其中xxx为3位班级编码";
        }
        
        // 2. 提取班级编码并校验班级是否存在
        String classCode = matcher.group(1);
        EduClass eduClass = new EduClass();
        eduClass.setClassCode(classCode);
        List<EduClass> classList = eduClassMapper.selectEduClassList(eduClass);
        if (classList == null || classList.isEmpty()) {
            return "班级不存在，导入失败";
        }
        eduClass = classList.get(0);
        
        try {
            // 3. 使用ExcelUtil读取Excel文件
            ExcelUtil<EduStudent> util = new ExcelUtil<>(EduStudent.class);
            List<EduStudent> studentList = util.importExcel(file.getInputStream());
            
            // 4. 批量导入学生数据
            int successNum = 0;
            int updateNum = 0;
            int insertNum = 0;
            
            for (EduStudent student : studentList) {
                // 处理性别映射
                if (student.getSex() != null) {
                    String sexStr = student.getSex().trim();
                    if ("男".equals(sexStr)) {
                        student.setSex("0");
                    } else if ("女".equals(sexStr)) {
                        student.setSex("1");
                    } else {
                        student.setSex("2"); // 未知
                    }
                } else {
                    student.setSex("2"); // 默认未知
                }
                
                // 设置班级ID
                student.setClassId(String.valueOf(eduClass.getClassId()));
                // 设置入学状态为在读
                student.setStatus("0");
                
                // 根据学号学生姓名+班级
                EduStudent existStudent = new EduStudent();
                //existStudent.setStudentNo(student.getStudentNo());
                existStudent.setStudentName(student.getStudentName());
                existStudent.setClassId(classCode);
                existStudent.setDelFlag("0");
                List<EduStudent> existStudents = eduStudentMapper.selectEduStudentList(existStudent);
                
                if (existStudents != null && !existStudents.isEmpty()) {
                    // 学生已存在，更新信息
                    EduStudent updateStudent = existStudents.get(0);
                    updateStudent.setStudentName(student.getStudentName());
                    updateStudent.setEnglishName(student.getEnglishName());
                    updateStudent.setSex(student.getSex());
                    updateStudent.setContactPhone(student.getContactPhone());
                    updateStudent.setClassId(String.valueOf(eduClass.getClassId()));
                    updateStudent.setUpdateTime(DateUtils.getNowDate());
                    
                    eduStudentMapper.updateEduStudent(updateStudent);
                    updateNum++;
                    successNum++;
                } else {
                    // 学生不存在，新增
                    student.setCreateTime(DateUtils.getNowDate());
                    student.setStudentNo(StudentNoUtils.generateStudentNo(classCode));
                    eduStudentMapper.insertEduStudent(student);
                    insertNum++;
                    successNum++;
                    
                    // 新增学生时，更新班级学生人数
                    eduClassService.updateStudentCount(classCode, 1);
                }
            }
            
            return "成功导入 " + successNum + " 条学生数据（新增 " + insertNum + " 条，更新 " + updateNum + " 条）";
        } catch (Exception e) {
            e.printStackTrace();
            return "导入失败：" + e.getMessage();
        }
    }
}
